# -*- coding: utf-8 -*-
"""
Created on Tue Oct 10 22:39:02 2017

@author: Luther
"""

import requests
import os
import re
import time

data = {}
data['f'] = 'auto'
data['t'] = 'auto'


def getHTMLjson(url):
    try:
        r = requests.post(url, data=data)
        r.raise_for_status()
        r.encoding = r.apparent_encoding
        return r.json()
    except:
        return '产生异常！'


def translate(word):
    url = 'http://fy.iciba.com/ajax.php?a=fy'
    dict = getHTMLjson(url)
    mean = ''.join(dict['content']['word_mean'])
    mean_list = re.findall(r'[\u4e00-\u9fa5]+', mean)
    return mean_list


with open(r'D:\word.txt', 'r') as f:
    word_list = f.read().split()

i = 1
for word in word_list:
    data['w'] = word
    print('正在查询第', i, '个单词...')
    with open(r'D:\results.csv', 'a') as f1:
        try:
            mean_list = translate(word)
            for result in mean_list:
                f1.write(word.lower())
                f1.write(',')
                f1.write(result)
                f1.write('\n')
            print('查询成功！')
        except:
            f1.write(word.lower())
            f1.write(',')
            f1.write('ERROR!!!')
            f1.write('\n')
            print('查询失败！')
    i = i + 1
    #time.sleep(2)

print('Finished!')
